package com.ruoyi.repairCar.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.repairCar.domain.dto.RescueMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


// 延迟队列处理（范围扩大）
@Component
@RequiredArgsConstructor
class DelayQueueHandler {
    private final RabbitTemplate rabbitTemplate;
    private final StringRedisTemplate redisTemplate;
    private static final String MQ_PREFIX = "rescue.task:";

    @RabbitListener(queues = "delay.queue")
    public void handleDelayMessage(String message) {
        try {
            RescueMessage msg = parseMessage(message);
            String messageKey = MQ_PREFIX + msg.getMessageId();

            // 获取当前状态
            Map<Object, Object> state = redisTemplate.opsForHash().entries(messageKey);
            int currentRange = Integer.parseInt((String) state.get("current_range"));
            int retryCount = Integer.parseInt((String) state.get("retry_count"));
            int maxRange = 3; // 从原始请求获取更合理

            if (currentRange < maxRange) {
                // 更新重试状态
                Map<String, String> updateState = new HashMap<>();
                updateState.put("current_range", String.valueOf(currentRange + 1));
                updateState.put("retry_count", String.valueOf(retryCount + 1));
                redisTemplate.opsForHash().putAll(messageKey, updateState);

                // 重新发送扩大范围的消息
                rabbitTemplate.convertAndSend(
                        "rescue.exchange",
                        String.format("rescue.%dkm", currentRange + 1),
                        message,
                        m -> {
                            m.getMessageProperties().setExpiration("15000");
                            return m;
                        });
            } else {
                // 触发最终处理逻辑
//                handleFinalAttempt(msg);
                System.out.println("最终处理逻辑");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析消息为RescueMessage对象
     *
     * @param message JSON格式的字符串消息
     * @return 解析后的RescueMessage对象
     * @throws IOException 如果解析失败
     */
    private RescueMessage parseMessage(String message) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(message, RescueMessage.class);
    }

}
